#include "edit_form.h"
#include "ui_edit_form.h"
#include <QFile>
#include <QDebug>
#include <QRegExp>

static QString filePathInput = "json.json";

edit_form::edit_form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::edit_form)
{
    ui->setupUi(this);
    setWindowTitle("qml自动化编辑器");
    init();
}

edit_form::~edit_form()
{
    delete ui;
}

void edit_form::showWidget()
{
    this->show();
}

void edit_form::init()
{
    _state = State_Idle;
    ui->pushButton_3->setEnabled(false);
    ui->pushButton_4->setEnabled(false);

    _add_form = new Add_Form();
    _smallTool = new SmallTool();

    connect(_add_form, &Add_Form::addData, this, &edit_form::addData);
    connect(ui->listWidget, &QListWidget::currentRowChanged, this, [=](){
//        _state = State_Idle;
        ui->pushButton_3->setEnabled(true);
        ui->pushButton_4->setEnabled(true);
    });

    QString data = _smallTool->readFile(filePathInput);
    parseJson(data);
    initListWidget();
}

void edit_form::addData(QVariant data)
{
    //
    if(_state == State_Add){
        _inputList.append(data.toMap());
        ui->listWidget->addItem(data.toMap().value("tip").toString());
    }
    else if(_state == State_Edit){
        int index = ui->listWidget->currentRow();
        _inputList[index] = data.toMap();
        ui->listWidget->item(index)->setText(data.toMap().value("tip").toString());
    }
    _state = State_Idle;
}

void edit_form::on_pushButton_clicked()
{
    saveData();
}

void edit_form::parseJson(QString data)
{
    if(!data.isEmpty()){
        QJsonParseError err;
        QJsonDocument document = QJsonDocument::fromJson(data.toUtf8(), &err);
        if(err.error == QJsonParseError::NoError){
            QVariant inputData = document.toVariant();
            _inputList = inputData.toList();
        }
        else{
            qWarning()<<err.error<<err.errorString();
        }
    }
}

void edit_form::initListWidget()
{
    int len = _inputList.length();
    for(int i=0; i<len; i++){
        ui->listWidget->addItem(_inputList.at(i).toMap().value("tip").toString());
    }
}

void edit_form::saveData()
{
    QJsonDocument document = QJsonDocument::fromVariant(_inputList);
    _smallTool->writeFile(QString(document.toJson()), filePathInput);
}
void edit_form::on_pushButton_2_clicked()
{
    //add
    _state = State_Add;
    _add_form->showWidget(QVariant());
}

void edit_form::on_pushButton_3_clicked()
{
    //edit
    _state = State_Edit;
    if(ui->listWidget->currentRow() == -1) return;
    _add_form->showWidget(_inputList.at(ui->listWidget->currentRow()));
}

void edit_form::on_pushButton_4_clicked()
{
    //del
    _state = State_Del;
    if(ui->listWidget->currentRow() == -1) return;
    _inputList.takeAt(ui->listWidget->currentRow());
    ui->listWidget->takeItem(ui->listWidget->currentRow());

    if(ui->listWidget->count() == 0){
        ui->pushButton_3->setEnabled(false);
        ui->pushButton_4->setEnabled(false);
    }
}
